package kevin.study.zephyr.demo.service.impl;

import kevin.study.zephyr.demo.service.DesignService;
import kevin.study.zephyr.domain.model.Field;
import kevin.study.zephyr.domain.model.Form;
import kevin.study.zephyr.domain.model.entity.IntegerEntity;
import kevin.study.zephyr.domain.model.entity.TextEntity;
import kevin.study.zephyr.domain.model.view.View;
import kevin.study.zephyr.exceptions.EndlessLoopException;
import kevin.study.zephyr.platform.Platform;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * HISTORY
 *
 * @author Kevin.Huang
 * @createtime 2008-3-18 下午04:16:23
 */
public class DesignServiceImpl implements DesignService {

    public void createForm() {
        Form form = new Form();
        form.setName("Test");
        // 为这个Form添加一系列Field
        Field field1 = new Field();
        field1.setName("Name");
        field1.setType(TextEntity.class.getName());

        Field field2 = new Field();
        field2.setName("Age");
        field2.setType(IntegerEntity.class.getName());

        Field field3 = new Field();
        field3.setName("Address");
        field3.setType(TextEntity.class.getName());

        Collection<Field> fields = new ArrayList<Field>();
        fields.add(field1);
        fields.add(field2);
        fields.add(field3);
        // 将Field注入Form
        form.setFields(fields);
        // 以上Form设计完毕
        // 保存Form
        try {
            form.save();
        } catch (EndlessLoopException e) {
            // 现在不会出现此异常,当Form设计出现死循环时,将无法保存,并抛出此异常
            throw new RuntimeException("此次不会运行到这里!");
        }
    }

    public Collection<Form> listAllForm() {
        List<Form> list = Platform.getFormManager().getFormDAO().findAll();
        Collection<Form> result = new ArrayList<Form>();
        for (Form f : list) {
            result.add(f);
        }
        return result;
    }

    public void deleteForm(String uuid){
         Platform.getFormManager().getFormDAO().delete(uuid);
    }

    public Collection<View> listAllView() {
        List<View> list = Platform.getViewManager().getViewDAO().findAll();
        Collection<View> result = new ArrayList<View>();
        for (View f : list) {
            result.add(f);
        }
        return result;
    }

}
